﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using HalconDotNet;
namespace halcon检测项目
{
    //CSV属于报表文件，适用于工程检测完之后的数据整理
    //项目中如果有相关需要可以直接引入该文件
    internal class CSVApi
    {
        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="data"></param>
        /// <param name="result"></param>
        public void SaveData(string data,string result)
        {
            string path =Directory.GetCurrentDirectory()+"\\Data";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            //后缀名代表文件的格式
            string fileName = $"{path}\\{DateTime.Now.ToString("MM-dd")}.csv";
            if (!File.Exists(fileName)) {
                //第一次创建文件并存储
                //数据流
                FileStream fs = new FileStream(fileName,FileMode.Create,FileAccess.Write);
                StreamWriter sw =new StreamWriter(fs,Encoding.Default);
                //考虑到文件时持续的，使用追加方式
                StringBuilder stringBuilder = new StringBuilder();
                //"表头"
                stringBuilder.Append("时间").Append(",").Append("测量项目").Append(",").Append("测量结果") ;
                sw.WriteLine(stringBuilder);
                sw.Close();
                sw.Dispose();
                fs.Close();
                fs.Dispose();

            }
            //文件存在，直接追加
            using (StreamWriter sw =new StreamWriter(fileName,true, Encoding.Default))
            {
                StringBuilder stringBuilder = new StringBuilder();
                //"表头"
                stringBuilder.Append(DateTime.Now.ToString("HH-mm-ss")).Append(",").Append(data).Append(",").Append(result);
                sw.WriteLine(stringBuilder);
            }

        }

        /// <summary>
        /// 失败整理成日志
        /// </summary>
        /// <param name="logInfo"></param>
        public void SaveLog(string logInfo)
        {
         string _logPath =Directory.GetCurrentDirectory()+"\\log";
            if (!Directory.Exists(_logPath))
            {
                Directory.CreateDirectory(_logPath);
            }
            string fileName = $"{_logPath}\\{DateTime.Now.ToString("MM-dd")}._log.txt";
            if (!File.Exists(fileName))
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    using (StreamWriter sw =new StreamWriter(fs))
                    {
                        sw.WriteLine(logInfo);
                    }
                }
            }
            else
            {
                using (StreamWriter sw = new StreamWriter(fileName,true))
                {
                    sw.WriteLine(logInfo);
                }
            }

        }
    }

}
